import * as signalR from '@microsoft/signalr'
import { ALL } from '@/api/baseUrl'
import setUpTime from '@/utils/setUpTime'

let connection
export function signalRConnect(name,tableData) {
  // 获取设备测点实时数据
  connection = new signalR.HubConnectionBuilder().withUrl(`${ALL}/signalr`, {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
  }).build()
  connection.start()
  console.log('开始链接signalR----->')
  connection.on(name, message => {

    // 接收signalr数据
    const {
      BarWheelMachineCode,
      MeasurePointCode,
      IsError,
      LastModificationTime,
      ShockValue,
      TemperValue
    } = JSON.parse(message)
    console.log('接收signalR消息----->', JSON.parse(message), localStorage.BarWheelMachineCode)
    if (BarWheelMachineCode === localStorage.BarWheelMachineCode) {
      tableData.forEach(item => {
        if (item.measurePointCode === MeasurePointCode) {
          item.shockValue = ShockValue,
          item.temperValue = TemperValue,
          item.isError = IsError,
          item.lastModificationTime = setUpTime.formatTime(LastModificationTime)
        }
      })
    }

    // 按时间排序
    tableData.sort(function (a, b) {
      return b.lastModificationTime < a.lastModificationTime
    })
  })
  connection.onclose(() => {
    setTimeout(() => {
      connection.start()
    }, 5000)
  })
}

export function signalRClose(name) {
  connection.value.off(name)
}